home *** CD-ROM | disk | FTP | other *** search
- Path: geog41.umd.edu!cosmo
- From: cosmo@Glue.umd.edu (Peter John Ersts)
- Newsgroups: comp.lang.c++
- Subject: Re: Memory allocation.
- Date: 10 Feb 1996 21:00:28 GMT
- Organization: Project GLUE, University of Maryland, College Park, MD
- Message-ID: <4fj11c$j04@mojo.eng.umd.edu>
- References: <1996Feb10.161530.26449@wisipc.weizmann.ac.il>
- NNTP-Posting-Host: geog41.umd.edu
- X-Newsreader: TIN [version 1.2 PL2]
-
- Kajdan Dimitry (cerlpvk) wrote:
- : I'm a starter so the question may seem stupid.
-
- : Would someone explain why this program works?
-
- : int* func()
- : {
- :
- :
- : int b[10];
- : for(int i=0;i<9;i++)
- : b[i]=i;
- : return b;
- : }
-
- : int main(){
- :
- : int* x= func();
- :
- :
- : cout<<x[2]<<endl;
- : return(1);
- : }
-
- : The point is that b is allocated on the stack i.e without "new".
-
- : Thanks in advance.
-
-
-
- It works because x is an integer pointer and func() returns an integer
- pointer. b gets allocated when the functions is called.
- : int* func()
- : {
- : int b[10];
- *snip*
-
-
- If you want to pass an array around you can basically just pass a pointer
- to the begining of the array and reference as normal. There is a problem
- with this piece of code, because b has gone out of scope, i.e is the memory
- allocated for b[10] as been "put back" into the free memory pool. It
- just happens that the correct values are still there because nothing else
- has been done that needs memory.
-
-
-
-
- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- Peter J. Ersts | PHONE-HOME: (301)-422-9013
- Student For Life | PHONE-WORK: *************
- University of Maryland, College Park | E-MAIL: cosmo@eng.umd.edu
- ________________________________________| stinger@wam.umd.edu
-
- "They can't send us to hell, because we'd put it out"
-
- -Quote from a smokejumper getting on a bus to go back to base camp-
- +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-
-